package dao.impl;

import dao.UserDao;
import domain.User;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import utils.JDBCUtils;
import utils.LyyLogUtil;

import java.util.Date;

public class UserDaoImpl implements UserDao {
    private JdbcTemplate template=new JdbcTemplate(JDBCUtils.getDataSource());

    @Override
    public boolean register(User user) {
        String sql="insert into user values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
        int update=0;
        try {
            update = template.update(sql, null,user.getRealName(),user.getUserName(),
                    user.getPhoneNum(),user.getPassword(),new Date(),user.getExperience(),
                    user.getRank(),user.getGold(),user.getEmail(),user.getAddress(),user.getGender(),
                    user.getAge(),user.getCertificateNo(),user.getCertificateType());
        } catch (Exception e) {
            LyyLogUtil.logeE(e.getMessage());
        }
        return update!=0;
    }

    @Override
    public User login(String userName, String password) throws Exception{
        String sql="select * from user where userName=? and password=?";
        User user = template.queryForObject(sql, new BeanPropertyRowMapper<User>(User.class), userName, password);
        return user;
    }

    @Override
    public User queryByUsername(String userName) {
        String sql="select * from user where userName=?";
        User user = null;
        try {
            user = template.queryForObject(sql, new BeanPropertyRowMapper<User>(User.class), userName);
        } catch (Exception e) {
            LyyLogUtil.logeE(e.getMessage());
        }
        return user;
    }

    @Override
    public boolean updateUserInfo(User user) throws Exception {
        String sql="update user set realName=?,phoneNum=?,email=?," +
                "address=?,gender=?,age=?,certificateNo=?,certificateType=? where userName=? and password=?";
        int update=0;
        try {
             update= template.update(sql, user.getRealName(), user.getPhoneNum(), user.getEmail(), user.getAddress(), user.getGender(), user.getAge(),
                    user.getCertificateNo(), user.getCertificateType(), user.getUserName(), user.getPassword());
        } catch (Exception e) {
            LyyLogUtil.logeE("修改用户信息失败："+e.getMessage());
        }
        return update!=0;
    }

    @Override
    public boolean addUserExperience(String userId,int experi) throws Exception {
        String sql="update user set experience=(experience+?) where id=?";
        int update = 0;
        try {
            update = template.update(sql, experi, userId);
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }
        return update!=0;
    }


}
